package com.zhijiang.util;

import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Base64;

//二维码生成
public class QRCodeUtil {

    public static String getCode(String codeUrl) {
        // 二维码内容
        String url = codeUrl;
        // 生成二维码并指定宽高
        BufferedImage generate = QrCodeUtil.generate(url, 300, 300);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(generate, "jpg", os);
        } catch (IOException e) {
            return e.getMessage();
        }
        //如果二维码要在前端显示需要转成Base64
        return Base64.getEncoder().encodeToString(os.toByteArray());
    }

    public static void main(String[] args) {
        String url = "111111111111222222222222222222222222222222三国大会";
        String code = QRCodeUtil.getCode(url);
        System.out.println(code);
    }

    /* 高度——height，
宽度——width，
二维码内容——text（url需要自动跳转前面加上https://）
背景图片的路径——filePath*/
    public static void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);

        Path path = FileSystems.getDefault().getPath(filePath);

        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

    }

}
